<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Thumb extends CI_Controller {
	public function index($file) {
		$file = str_replace(":", "/", $file);
		
		if (file_exists(".".$file)) {
			$md = md5($file);
			$livetime = 0;
			$have = false;
			$cachefile = './uploads/thumbcache/'.$md;
			if (file_exists($cachefile)) {
				$livetime = time() - filectime($cachefile);
				$t = filectime($cachefile);
				$have = true;
			}
			//$request = getallheaders();
			if (isset($request['If-Modified-Since'])) {
			   $modifiedSince = explode(';', $request['If-Modified-Since']);
			   $modifiedSince = strtotime($modifiedSince[0]);
			} else {
			   $modifiedSince = 0;
			}

			if ($modifiedSince != 0 && $modifiedSince > $t) { header('HTTP/1.1 304 Not Modified'); exit(); }

			//$have = false;
			if ($have == true && $livetime < 2592000) {
				header('Expires: '.gmdate('D, d M Y H:i:s', $t + 2592000) . ' GMT');
				header('Last-Modified: '.gmdate('D, d M Y H:i:s', $t) . ' GMT');
				header("Cache-Control: public");
				$im = getimagesize(".".$cachefile);
				$t = str_replace("image/", "", $im['mime']);
				$this->output->set_content_type($t)->set_output(file_get_contents($cachefile));
			} else {
				header('Expires: '.gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
				header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()) . ' GMT');
				header("Cache-Control: public");
				$this->load->library('thumbnail');
				$im = getimagesize(".".$file);
				$this->thumbnail->output(".".$file, $cachefile, array('width' => '200', 'height' => '200', 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
				$t = str_replace("image/", "", $im['mime']);
				$this->output->set_content_type($t)->set_output(file_get_contents($cachefile));
			}
		} else {
			$this->output->set_status_header(404);
		}
	}
	public function tools($captcha_id, $rand = null) {
      include($_SERVER['DOCUMENT_ROOT'].'/application/libraries/kcaptcha/kcaptcha.php');
//	  $key = sha1("soltbyme".$this->session->userdata('session_id')."myhashsolt");

      $captcha = new KCAPTCHA();
	  $p_data['captcha_id'] = 0;
	  $p_data['captcha_session'] = $captcha_id;
	  $p_data['captcha_code'] = $captcha->getKeyString();
	  $p_data['captcha_date'] = time();
	  $this->db->insert('captcha', $p_data);
	  $expire = time() - 600;
	  $this->db->where('captcha_date < ', $expire)->delete('captcha');
	}
}